package com.palm.core.util.castor;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface Castor<T> {
    T cast(Object v);
    static<T> void register(Class<T> type, Castor<T> castor){
        Casters.register(type,castor);
    }
    static <T> T castTo(Object obj, Class<T> type){
        if(obj !=null&&type.isInstance(obj)){
            return (T)obj;
        }
        return Casters.castTo(obj,type);
    }
    static <T> Castor<T> getCastor(Class<T> type){
        return Casters.getCastor(type);
    }
}

class Casters{
    private static Map<Class, Castor> castorMap=new HashMap<>();
    static<T> void register(Class<T> type, Castor<T> castor){
        castorMap.put(type,castor);
    }
    static<T> T castTo(Object obj, Class<T> type){
        Castor<T> c=getCastor(type);
        if(c!=null){
            return c.cast(obj);
        }
        return null;
    }
    static <T> Castor<T> getCastor(Class<T> type){
        return castorMap.get(type);
    }
    static {
        register(Boolean.TYPE, BooleanCastor.instance);
        register(Boolean.class, BooleanCastor.instance);
        register(Date.class,DateCastor.instance);
        register(Double.class,DoubleCastor.instance);
        register(Double.TYPE,DoubleCastor.instance);
        register(Integer.TYPE,IntCastor.instance);
        register(Integer.class,IntCastor.instance);
        register(Long.TYPE,LongCastor.instance);
        register(Long.class,LongCastor.instance);
        register(Float.TYPE,FloatCastor.instance);
        register(Float.class,FloatCastor.instance);
        register(String.class, StringCastor.instance);
        register(BigDecimal.class,BigDecimalCastor.instance);
        register(Map.class,MapCastor.instance);
        register(List.class,ListCastor.instance);
    }
}
